﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data;
using System.Data.OleDb;
using System.Collections.ObjectModel;
using libConn;
using System.IO;
using CodeReason.Reports;
using System.Windows.Xps.Packaging;
using Microsoft.Win32;

namespace ApartmentSale
{
	public partial class Deposit : Window
	{
		public Deposit()
		{
			this.InitializeComponent();
		}

        private bool getData()
        {
            string errMessage = null;
            string str = "Select * From deposit";

            DataTable oleDT;
            oleDT = libConn.AccdbConn.query(str, ref errMessage);

            if (errMessage != null)
            {
                System.Windows.MessageBox.Show(
                    errMessage,
                    "Deposit data read error",
                    System.Windows.MessageBoxButton.OK,
                    System.Windows.MessageBoxImage.Error);
                return false; ;
            }

            ObservableCollection<DepositView> deposit = new ObservableCollection<DepositView>();

            foreach (DataRow r in oleDT.Rows)
            {
                deposit.Add(new DepositView()
                {
                    deposit_id = Convert.ToInt32(r["deposit_id"]),
                    deposit_status = Convert.ToInt32(r["deposit_status"]),
                    receipt_id = Convert.ToInt32(r["receipt_id"]),
                    receipt_code = r["receipt_code"].ToString().Replace("''", "'"),
                    deposit_apartment_code = r["deposit_apartment_code"].ToString().Replace("''", "'"),
                    deposit_amount = Convert.ToDouble(r["deposit_amount"]),
                    deposit_custom_name = r["deposit_custom_name"].ToString().Replace("''", "'"),
                    deposit_custom_contact = r["deposit_custom_contact"].ToString().Replace("''", "'"),
                    deposit_create_date = Convert.ToDateTime(r["deposit_create_date"]),
                    apartment_id = Convert.ToInt32(r["apartment_id"])
                });
            }

            dataGrid.DataContext = deposit;

            return true;
        }

        private bool getData(DateTime begin, DateTime end)
        {
            string errMessage = null;
            string str = "Select * From deposit WHERE deposit_create_date BETWEEN #"
                + begin.ToShortDateString()
                + "# AND #"
                + end.AddDays(1).ToShortDateString()
                + "#";

            DataTable oleDT;
            oleDT = libConn.AccdbConn.query(str, ref errMessage);

            if (errMessage != null)
            {
                System.Windows.MessageBox.Show(
                    errMessage,
                    "Deposit data read error",
                    System.Windows.MessageBoxButton.OK,
                    System.Windows.MessageBoxImage.Error);
                return false; ;
            }

            ObservableCollection<DepositView> deposit = new ObservableCollection<DepositView>();

            foreach (DataRow r in oleDT.Rows)
            {
                deposit.Add(new DepositView()
                {
                    deposit_id = Convert.ToInt32(r["deposit_id"]),
                    deposit_status = Convert.ToInt32(r["deposit_status"]),
                    receipt_id = Convert.ToInt32(r["receipt_id"]),
                    receipt_code = r["receipt_code"].ToString().Replace("''", "'"),
                    deposit_apartment_code = r["deposit_apartment_code"].ToString().Replace("''", "'"),
                    deposit_amount = Convert.ToDouble(r["deposit_amount"]),
                    deposit_custom_name = r["deposit_custom_name"].ToString().Replace("''", "'"),
                    deposit_custom_contact = r["deposit_custom_contact"].ToString().Replace("''", "'"),
                    deposit_create_date = Convert.ToDateTime(r["deposit_create_date"]),
                    apartment_id = Convert.ToInt32(r["apartment_id"])
                });
            }

            dataGrid.DataContext = deposit;

            return true;
        }

        private bool getApartment(int apartment_id, out ApartmentView apartment)
        {
            string errMessage = null;
            string str = "SELECT * FROM apartments WHERE apartment_id = " + apartment_id;

            DataTable oleDT;
            oleDT = libConn.AccdbConn.query(str, ref errMessage);

            if (errMessage != null && oleDT.Rows.Count < 1)
            {
                System.Windows.MessageBox.Show(
                    errMessage,
                    "Deposit data read error",
                    System.Windows.MessageBoxButton.OK,
                    System.Windows.MessageBoxImage.Error);
                apartment = null;
                return false;
            }

            DataRow r = oleDT.Rows[0];
            apartment = new ApartmentView(r);

            return true;
        }

        private void btAdd_Click(object sender, RoutedEventArgs e)
        {
            DepositEdit dialog = new DepositEdit();
            dialog.ShowDialog();
            getData();
        }

        private void dataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (dataGrid.SelectedIndex == -1)
                return;

            var deposit = dataGrid.SelectedItem as DepositView;
            if (deposit != null)
            {
                DepositEdit dialog = new DepositEdit(deposit);
                dialog.ShowDialog();
                getData();
            }
        }

        private void btModify_Click(object sender, RoutedEventArgs e)
        {
            if (dataGrid.SelectedIndex == -1)
                return;

            var deposit = dataGrid.SelectedItem as DepositView;
            if (deposit != null)
            {
                DepositEdit dialog = new DepositEdit(deposit);
                dialog.ShowDialog();
                getData();
            }
        }

        private void btDelete_Click(object sender, RoutedEventArgs e)
        {
            if (dataGrid.SelectedIndex == -1)
                return;

            var deposit = dataGrid.SelectedItem as DepositView;
            if (deposit != null)
            {
                if (deposit.deposit_status == 1)
                {
                    System.Windows.MessageBox.Show(
                        "The current deposit is deducted paying back the principal, in the main window choose to be booking the house, and then in the 'Receipt' tab to remove reservations.",
                        "Remove prohibited",
                        System.Windows.MessageBoxButton.OK,
                        System.Windows.MessageBoxImage.Stop);
                    return;
                }

                ApartmentView apartment;
                if (!getApartment(deposit.apartment_id, out apartment))
                    return;

                if (apartment.apartment_status == 2)
                {
                    System.Windows.MessageBox.Show(
                        "The current deposit is deducted paying back the principal, in the main window choose to be booking the house, and then in the 'Receipt' tab to remove reservations.",
                        "Remove prohibited",
                        System.Windows.MessageBoxButton.OK,
                        System.Windows.MessageBoxImage.Stop);
                    return;
                }

                if (MessageBox.Show("Sure you want to delete the deposit records? \n This action can not be recovered!",
                    "Delete", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No)
                    return;

                string errMessage = null;
                string str = "DELETE FROM deposit WHERE deposit_id = " + deposit.deposit_id;

                libConn.AccdbConn.exec(str, ref errMessage);

                if (errMessage != null)
                {
                    System.Windows.MessageBox.Show(
                        errMessage,
                        "Remove the deposit failed",
                        System.Windows.MessageBoxButton.OK,
                        System.Windows.MessageBoxImage.Error);
                    return;
                }

                str = "DELETE FROM receipt WHERE receipt_id = " + deposit.receipt_id;

                libConn.AccdbConn.exec(str, ref errMessage);

                if (errMessage != null)
                {
                    System.Windows.MessageBox.Show(
                        errMessage,
                        "Remove the deposit failed",
                        System.Windows.MessageBoxButton.OK,
                        System.Windows.MessageBoxImage.Error);
                    return;
                }

                if (apartment.apartment_status == 1)
                {
                    apartment.apartment_status = 1;
                    errMessage = apartment.Update();

                    if (errMessage != null)
                    {
                        System.Windows.MessageBox.Show(
                            errMessage,
                            "Remove the deposit, failed to modify apartment data",
                            System.Windows.MessageBoxButton.OK,
                            System.Windows.MessageBoxImage.Error);
                    }
                }

                getData();
            }

        }

        private void btQuery_Click(object sender, RoutedEventArgs e)
        {
            if (dpBegin.SelectedDate == null || dpEnd.SelectedDate == null)
            {
                getData();
                return;
            }

            if (dpBegin.SelectedDate > dpEnd.SelectedDate)
            {
                MessageBox.Show("As of the date of the start date not before.");
                dpEnd.Focus();
                return;
            }

            getData((DateTime)dpBegin.SelectedDate, (DateTime)dpEnd.SelectedDate);

        }

        private void btClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (!getData())
                this.Close();
        }

        private void btPrint_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.Cursor = Cursors.AppStarting;
                ReportDocument reportDocument = new ReportDocument();

                StreamReader reader = new StreamReader(new FileStream(@"Templates\DepositReport.xaml", FileMode.Open, FileAccess.Read));
                reportDocument.XamlData = reader.ReadToEnd();
                reportDocument.XamlImagePath = System.IO.Path.Combine(Environment.CurrentDirectory, @"Templates\");
                reader.Close();

                ReportData data = new ReportData();

                // set constant document values
                data.ReportDocumentValues.Add("PrintDate", DateTime.Now); // print date is now

                DataTable table = GetDataTable();

                data.DataTables.Add(table);

                XpsDocument xps = reportDocument.CreateXpsDocument(data);

                ReportPreview dialog = new ReportPreview();
                dialog.DocView.Document = xps.GetFixedDocumentSequence();

                // show the elapsed time in window title
                dialog.Title = "Deposit information";

                this.Cursor = Cursors.Arrow;
                dialog.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\r\n\r\n" + ex.GetType() + "\r\n" + ex.StackTrace, ex.GetType().ToString(), MessageBoxButton.OK, MessageBoxImage.Stop);
            }

        }

        private DataTable GetDataTable()
        {
            DataTable table = new DataTable("Data Table");

            // Declare variables for DataColumn and DataRow objects.
            DataColumn column;
            DataRow row;

            // Create new DataColumn, set DataType,
            // ColumnName and add to DataTable.   
            column = new DataColumn();
            column.DataType = Type.GetType("System.String");
            column.ColumnName = "code";
            column.Caption = "Receipt Sn";
            column.ReadOnly = true;
            column.Unique = true;
            // Add the Column to the DataColumnCollection.
            table.Columns.Add(column);

            // Create second column.
            column = new DataColumn();
            column.DataType = Type.GetType("System.String");
            column.ColumnName = "status";
            column.AutoIncrement = false;
            column.Caption = "Status";
            column.ReadOnly = false;
            column.Unique = false;
            // Add the column to the table.
            table.Columns.Add(column);

            //Create third column
            column = new DataColumn();
            column.DataType = Type.GetType("System.String");
            column.ColumnName = "amount";
            column.AutoIncrement = false;
            column.Caption = "Amount";
            column.ReadOnly = false;
            column.Unique = false;
            // Add the column to the table.
            table.Columns.Add(column);


            //Create forth column
            column = new DataColumn();
            column.DataType = Type.GetType("System.String");
            column.ColumnName = "apartment_code";
            column.AutoIncrement = false;
            column.Caption = "Apartment SN";
            column.ReadOnly = false;
            column.Unique = false;
            // Add the column to the table.
            table.Columns.Add(column);

            //Create forth column
            column = new DataColumn();
            column.DataType = Type.GetType("System.String");
            column.ColumnName = "name";
            column.AutoIncrement = false;
            column.Caption = "Custom";
            column.ReadOnly = false;
            column.Unique = false;
            // Add the column to the table.
            table.Columns.Add(column);

            //Create forth column
            column = new DataColumn();
            column.DataType = Type.GetType("System.String");
            column.ColumnName = "contact";
            column.AutoIncrement = false;
            column.Caption = "Contact";
            column.ReadOnly = false;
            column.Unique = false;
            // Add the column to the table.
            table.Columns.Add(column);

            //Create forth column
            column = new DataColumn();
            column.DataType = Type.GetType("System.String");
            column.ColumnName = "date";
            column.AutoIncrement = false;
            column.Caption = "Date";
            column.ReadOnly = false;
            column.Unique = false;
            // Add the column to the table.
            table.Columns.Add(column);

            // Make the ID column the primary key column.
            DataColumn[] PrimaryKeyColumns = new DataColumn[1];
            PrimaryKeyColumns[0] = table.Columns["code"];
            table.PrimaryKey = PrimaryKeyColumns;

            // Create three new DataRow objects and add
            // them to the DataTable

            foreach (DepositView deposit in dataGrid.Items)
            {
                row = table.NewRow();
                row["code"] = deposit.receipt_code;
                row["status"] = deposit.status_string;
                row["amount"] = deposit.deposit_amount.ToString("0.00");
                row["apartment_code"] = deposit.deposit_apartment_code;
                row["name"] = deposit.deposit_custom_name;
                row["contact"] = deposit.deposit_custom_contact;
                row["date"] = deposit.date_string;
                table.Rows.Add(row);
            }

            return table;
        }
	}
}